package com.ybw.config;

import com.ybw.annotation.CurrentTeacher;
import com.ybw.annotation.CurrentStudent;
import com.ybw.constant.AuthConstant;
import com.ybw.entity.Teacher;
import com.ybw.entity.Student;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * 用户解析器
 *
 * @author ybw
 * @version V1.0
 * @className CurrentUserResolver
 * @date 2023/11/4
 **/
@Slf4j
@Component
public class CurrentUserResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentStudent.class) || parameter.hasParameterAnnotation(CurrentTeacher.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        //1、请求header中有channel的值，根据channel解析出当前用户的信息
        HttpServletRequest httpServletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = httpServletRequest.getHeader(AuthConstant.TOKEN);
        Integer channel = httpServletRequest.getIntHeader(AuthConstant.CHANNEL);
        //2、channel的解析过程
        if (AuthConstant.STUDENT.equals(channel) && Student.class == parameter.getParameterType()) {
            return new Student(11L, "张三");
        } else if (AuthConstant.TEACHER.equals(channel) && Teacher.class == parameter.getParameterType()) {
            return new Teacher(12L, "李四");
        }
        return null;
    }
}
